package com.qys.livesMall.main.test;

/**
 * @packageName:
 * @className:OrderCancellationScheduler
 * @Description:
 * @author:guomx
 * @date:2023/7/718:13
 */

import io.netty.util.HashedWheelTimer;
import io.netty.util.Timeout;
import io.netty.util.TimerTask;

import java.time.Duration;
import java.util.concurrent.TimeUnit;

public class OrderCancellationScheduler {
    private final HashedWheelTimer timer;

    public OrderCancellationScheduler() {
        this.timer = new HashedWheelTimer();
    }

    public void scheduleCancellation(String orderId, Duration delay) {
        cancelOrder(orderId); // 先取消已存在的超时任务，以防重复调度

        TimerTask cancellationTask = timeout -> {
            cancelOrder(orderId); // 超时后执行取消订单的操作
        };

        Timeout timeout = timer.newTimeout(cancellationTask, delay.toMillis(), TimeUnit.MILLISECONDS);
    }

    public void cancelOrder(String orderId) {
        // 执行取消订单的逻辑
        System.out.println("Cancel order: " + orderId);
    }


    public static void main(String[] args) throws InterruptedException {
        OrderCancellationScheduler scheduler = new OrderCancellationScheduler();

        // 模拟创建订单并进行调度
        String orderId = "123456";
        Duration delay = Duration.ofSeconds(10); // 10秒后取消订单
        scheduler.scheduleCancellation(orderId, delay);

        // 保持程序运行一段时间
        Thread.sleep(15000);

        // 取消所有订单
    }
}

